<template>
	<view class="chat-container">
		<view class="chat-list" id="chatList" :style="{ paddingBottom: keyboardHeight + 'px' }">
			<view class="chat-date">{{currentDate}}</view>
			<view v-for="(item, index) in messageList" :key="index" class="chat-item" :class="{ 'chat-item-right': item.senderId === userId }">
				<view class="chat-avatar">
					<image :src="item.senderAvatar || '/static/default-avatar.png'"></image>
				</view>
				<view class="chat-content">
					<view class="chat-name" v-if="roomType === '1' && item.senderId !== userId">{{item.senderName}}</view>
					<view class="chat-message">{{item.content}}</view>
					<view class="chat-time">{{formatTime(item.sendTime)}}</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMoreMessages" @tap="loadMoreMessages">
				<text>加载更多消息</text>
			</view>
		</view>
		
		<view class="chat-input-wrapper" :style="{ bottom: keyboardHeight + 'px' }">
			<view class="chat-input-area">
				<input 
					class="chat-input"
					v-model="messageContent"
					confirm-type="send"
					:disabled="isSending"
					@confirm="sendMessage"
					@focus="onInputFocus"
					@blur="onInputBlur"
					placeholder="请输入消息"
				/>
				<button class="send-btn" :disabled="!messageContent || isSending" @tap="sendMessage">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				roomId: '',
				roomName: '',
				roomType: '',
				userId: '',
				messageList: [],
				messageContent: '',
				isSending: false,
				currentDate: this.formatDate(new Date()),
				keyboardHeight: 0,
				page: 1,
				pageSize: 20,
				hasMoreMessages: false,
				socketTask: null
			}
		},
		onLoad(options) {
			this.roomId = options.roomId;
			this.roomName = options.roomName;
			this.roomType = options.roomType;
			
			// 获取用户ID，确保有值
			const userId = uni.getStorageSync('userId');
			console.log('从缓存获取的userId:', userId);
			
			if (!userId) {
				// 如果没有用户ID，尝试从其他地方获取或提示用户登录
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo && userInfo.userId) {
					this.userId = userInfo.userId;
				} else {
					// 提示用户登录
					uni.showToast({
						title: '请先登录',
						icon: 'none',
						duration: 2000
					});
					
					// 3秒后返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 3000);
					return;
				}
			} else {
				this.userId = userId;
			}
			
			console.log('当前使用的userId:', this.userId);
			
			// 设置页面标题
			uni.setNavigationBarTitle({
				title: this.roomName
			});
			
			// 获取历史消息
			this.getHistoryMessages();
			
			// 建立WebSocket连接
			this.connectWebSocket();
		},
		onUnload() {
			// 页面卸载时关闭WebSocket连接
			if (this.socketTask) {
				this.socketTask.close();
			}
			
			// 标记消息为已读
			this.markMessagesAsRead();
		},
		methods: {
			connectWebSocket() {
				// 建立WebSocket连接
				this.socketTask = uni.connectSocket({
					url: this.$websocketUrl + '/chat/' + this.roomId + '?userId=' + this.userId,
					success: () => {
						console.log('WebSocket连接成功');
					}
				});
				
				// 监听连接打开
				this.socketTask.onOpen(() => {
					console.log('WebSocket连接已打开');
				});
				
				// 监听接收消息
				this.socketTask.onMessage((res) => {
					try {
						const message = JSON.parse(res.data);
						// 添加到消息列表
						this.messageList.push(message);
						// 滚动到底部
						this.scrollToBottom();
					} catch (e) {
						console.error('解析消息失败', e);
					}
				});
				
				// 监听连接关闭
				this.socketTask.onClose(() => {
					console.log('WebSocket连接已关闭');
				});
				
				// 监听连接错误
				this.socketTask.onError((res) => {
					console.error('WebSocket连接错误', res);
					uni.showToast({
						title: '聊天连接失败，请重试',
						icon: 'none'
					});
				});
			},
			getHistoryMessages() {
				// 获取历史消息
				const token = uni.getStorageSync('loginToken');
				const baseUrl = uni.$baseUrl || 'http://localhost:8080';
				uni.request({
					url: baseUrl + '/api/chat/messages',
					method: 'GET',
					data: {
						roomId: this.roomId,
						page: this.page,
						pageSize: this.pageSize
					},
					header: {
						'Authorization': `Bearer ${token}`
					},
					success: (res) => {
						if (res.data.code === 200) {
							const messages = res.data.data.list || [];
							// 将消息添加到列表前面
							this.messageList = [...messages, ...this.messageList];
							// 判断是否还有更多消息
							this.hasMoreMessages = messages.length >= this.pageSize;
							
							// 如果是第一页且有消息，滚动到底部
							if (this.page === 1 && messages.length > 0) {
								this.$nextTick(() => {
									this.scrollToBottom();
								});
							}
						}
					},
					fail: () => {
						uni.showToast({
							title: '获取聊天记录失败',
							icon: 'none'
						});
					}
				});
			},
			loadMoreMessages() {
				this.page++;
				this.getHistoryMessages();
			},
			sendMessage() {
				if (!this.messageContent.trim() || this.isSending) {
					return;
				}
				
				// 检查用户ID是否存在
				if (!this.userId) {
					uni.showToast({
						title: '用户ID不存在，请重新登录',
						icon: 'none'
					});
					return;
				}
				
				this.isSending = true;
				
				// 构造消息对象
				const message = {
					roomId: this.roomId,
					senderId: this.userId,
					content: this.messageContent,
					messageType: '1' // 文本消息
				};
				
				console.log('发送消息:', message);
				
				// 使用API发送消息
				const token = uni.getStorageSync('loginToken');
				const baseUrl = uni.$baseUrl || 'http://localhost:8080';
				uni.request({
					url: baseUrl + '/api/chat/messages',
					method: 'POST',
					data: message,
					header: {
						'Authorization': `Bearer ${token}`,
						'Content-Type': 'application/json'
					},
					success: (res) => {
						console.log('发送消息响应:', res.data);
						if (res.data.code === 200) {
							// 清空输入框
							this.messageContent = '';
							// 添加到消息列表
							this.messageList.push(res.data.data);
							// 滚动到底部
							this.scrollToBottom();
						} else {
							uni.showToast({
								title: res.data.msg || '发送失败，请重试',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('发送消息失败', err);
						uni.showToast({
							title: '发送失败，请重试',
							icon: 'none'
						});
					},
					complete: () => {
						this.isSending = false;
					}
				});
			},
			markMessagesAsRead() {
				// 标记消息为已读
				const token = uni.getStorageSync('loginToken');
				const baseUrl = uni.$baseUrl || 'http://localhost:8080';
				uni.request({
					url: baseUrl + '/api/chat/messages/read',
					method: 'PUT',
					data: {
						roomId: this.roomId
					},
					header: {
						'Authorization': `Bearer ${token}`
					}
				});
			},
			scrollToBottom() {
				// 滚动到底部
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#chatList').boundingClientRect();
					query.exec((res) => {
						if (res && res[0]) {
							uni.pageScrollTo({
								scrollTop: res[0].height,
								duration: 300
							});
						}
					});
				});
			},
			onInputFocus(e) {
				this.keyboardHeight = e.detail.height || 0;
				this.scrollToBottom();
			},
			onInputBlur() {
				this.keyboardHeight = 0;
			},
			formatTime(time) {
				if (!time) return '';
				
				const date = new Date(time);
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				
				return `${hours}:${minutes}`;
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				
				return `${year}-${month}-${day}`;
			}
		}
	}
</script>

<style lang="scss">
	.chat-container {
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom: 100rpx;
	}
	
	.chat-list {
		flex: 1;
		padding: 20rpx;
	}
	
	.chat-date {
		text-align: center;
		font-size: 24rpx;
		color: #999;
		margin: 30rpx 0;
	}
	
	.chat-item {
		display: flex;
		margin-bottom: 30rpx;
	}
	
	.chat-item-right {
		flex-direction: row-reverse;
		
		.chat-content {
			align-items: flex-end;
			margin-right: 20rpx;
			margin-left: 0;
			
			.chat-message {
				background-color: #1296db;
				color: #fff;
				border-radius: 20rpx 4rpx 20rpx 20rpx;
			}
		}
	}
	
	.chat-avatar {
		width: 80rpx;
		height: 80rpx;
		
		image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}
	
	.chat-content {
		display: flex;
		flex-direction: column;
		margin-left: 20rpx;
		max-width: 70%;
	}
	
	.chat-name {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 8rpx;
	}
	
	.chat-message {
		padding: 16rpx 24rpx;
		background-color: #fff;
		border-radius: 4rpx 20rpx 20rpx 20rpx;
		font-size: 28rpx;
		word-break: break-all;
		min-height: 28rpx;
	}
	
	.chat-time {
		font-size: 22rpx;
		color: #999;
		margin-top: 8rpx;
	}
	
	.load-more {
		text-align: center;
		font-size: 24rpx;
		color: #999;
		padding: 20rpx 0;
	}
	
	.chat-input-wrapper {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-top: 1rpx solid #eee;
	}
	
	.chat-input-area {
		display: flex;
		align-items: center;
	}
	
	.chat-input {
		flex: 1;
		height: 80rpx;
		background-color: #fff;
		border-radius: 40rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
	}
	
	.send-btn {
		width: 120rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		background-color: #1296db;
		color: #fff;
		border-radius: 35rpx;
		margin-left: 20rpx;
		font-size: 28rpx;
		padding: 0;
	}
	
	.send-btn[disabled] {
		background-color: #ccc;
	}
</style> 